<template>
    <CommonPage :tableConfig="option" ref="authorizationRef" formKey="authorizationAgreement"></CommonPage>
    <ElDialog v-model="dialog" width="600px" :title="title">
        <UiForm :formData="formData" @close="dialog = false" @callback="submitForm">
            <div>
                <el-upload 
                    v-model:file-list="fileList" 
                    class="upload-demo" 
                    drag 
                    :auto-upload="false" 
                    :limit="1" 
                    :on-exceed="fileExceed"
                    :on-change="handleChange">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        <p>请将协议文件拖拽上传或 <em>点击这里</em></p>
                        <div class="el-upload__tip">支持的文件类型：.PDF</div>
                    </div>
                </el-upload>
            </div>
        </UiForm>
    </ElDialog>
</template>
<script setup>
import CommonPage from '@/components/CommonPage/index.vue'
import {ElDialog, ElUpload, ElIcon, ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import UiForm from '@/components/uiForm.vue'
import { reactive, ref, computed } from 'vue';
import { UploadFilled } from '@element-plus/icons-vue'
import {authorizionStatus} from "@/utils/enum.js"
import {agreementSave, changeStatus} from "@/server/manage/channel.js"
import { paramsData } from '@/utils'
import {uploadFileMinio} from "@/server/common/files.js"

const dialog = ref(false)
const openType = ref()
const fileList = ref([])
const authorizationRef = ref()
let id = null
const option = reactive({
    // 0,待发布1,使用中2,已失效3,已归档4,删除
    operationWidth: 180,
    formItems: [
        {label: '文件名称', prop: 'agreementName', type: 'input', show: true},
        {label: '文件编号', prop: 'agreementCode', type: 'input', show: true},
        {label: '状态', prop: 'status', type: 'select', show: true, options: authorizionStatus},
    ],
    buttons: [
        {label: "新增", icon: 'Plus', auth: '', handle: (event)=> {handleOpen('add')}},
        // {label: "删除", icon: 'Delete', type: 'danger', handle: (event)=> {handleDel(event)}},
    ],
    options: [
        {label: '发布', handle: (event) => {handleStatus(event, 1)}, isShow:(row) => {return row.status == 0}},
        {label: '失效', handle: (event) => {handleStatus(event, 2)}, isShow:(row) => {return row.status == 1}},
        {label: '归档', handle: (event) => {handleStatus(event, 3)}, isShow:(row) => {return row.status == 2}},
        {label: '编辑', handle: (event) => {handleOpen('edit', event)}, isShow:(row) => {return ["2","0"].includes(row.status)}},
        {label: '删除', handle: (event) => {handleDel(event)}, isShow:(row) => {return ["2","3"].includes(row.status)}, type: 'danger'}
    ]
})
// 新增的表单参数
const formData = reactive([
    {label: "协议名称", type: 'input', key: "agreementName", value: '', required: true},
    {label: "版本号", type: 'input', key: "version", value: '', required: true},
    {label: "简要概述", type: 'input', key: "agreementSummary", widgetType: 'textarea', value: '', required: true}
])
const title = computed(() => {
    let obj = {add: '新增',edit: '编辑' }
    return obj[openType.value]
})
// 编辑赋值
const getDetail = (item) => {
    formData.forEach(next => {
        if(item[next.key]) next.value = item[next.key]

    })
    let fileName = item.fileUrl?item.fileUrl.substr(item.fileUrl.lastIndexOf("_")+1):"";
    fileList.value[0] = {url: item.fileUrl, type: "string", name: fileName}
    id = item.id
}
// 新增 编辑
const handleOpen = (type, item) => {
    openType.value = type
    if(item) getDetail(item)
    else {formData.forEach(next => next.value = "");fileList.value = []}
    dialog.value = true
}
// 超出文件个数限制提示
const fileExceed = () => {
    ElMessage.error('只能上传一个文件！')
}
// 图片发上变化
const handleChange = (res) => {
    let check = beforeAvatarUpload(res.raw)
    if(!check) fileList.value = []
}
// 文件检测
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== "application/pdf") {
        ElMessage.error('请上传pdf格式的文件')
        return false
    } else if (rawFile.size / 1024 / 1024 > 60) {
        ElMessage.error('文件不能大于60MB!')
        return false
    }
    return true
}
// 上传文件
const uploadFun = async() => {
    return new Promise((resolve, rejects) => {
        if(fileList.value[0].type === 'string') {resolve(fileList.value[0].url)}
        else{
            let formData = new FormData()
            formData.append("file", fileList.value[0].raw)
            uploadFileMinio(formData).then(res => {
                debugger
                resolve(res.data.fileUrl)
            }).catch(msg => {
                rejects(msg)
            })
        }
    })
}
// 提交
const submitForm = async(formData) => {
    if(fileList.value.length === 0){
        return ElMessage.error('请添加附件！')
    }
    const loadingInstance = ElLoading.service({lock: true,text: '提交中',background: 'rgba(0, 0, 0, 0.3)',})
    let url = await uploadFun()
    let params = formData
    params.fileUrl = url
    let type = {"add": "save", "edit": "update"}
    if(openType.value === "edit") params.id = id
    agreementSave(params, type[openType.value]).then(res => {
        loadingInstance.close()
        ElMessage({ message: "操作成功！", type: 'success'})
        authorizationRef.value.resetTableData()
        dialog.value = false
    })
}
// 改变状态
const handleStatus = (row, type) => {
    changeStatus({"id": row.id,"status": type}).then(res => {
        ElMessage({ message: "操作成功！", type: 'success'})
        authorizationRef.value.resetTableData()
    })
}
//删除
const handleDel = (row) => {
    ElMessageBox.confirm('您确定删除吗？','提示',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}
    ).then(() => {
        changeStatus({"id": row.id,"status": 4}).then(res => {
            ElMessage({ type: 'success', message: '删除成功！'})
            authorizationRef.value.resetTableData()
        })
    })
    .catch()
}
</script>